<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="disabled ? '变更' : form.pp_id ? '编辑' : '添加'" v-model="visible" align-center width="600px" :z-index="2000"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140">
      <div class="grid grid-cols-2 gap-x-3">
        <el-form-item label="sku" prop="sku" :rules="[{ required: true, message: '不能为空', trigger: 'change' }, { validator: skuValidate, trigger: 'change' }]">
          <el-input v-model.lazy="form.sku" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="平台" prop="platform" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.platform" :options="options.platform" select placeholder="平台" class="w-full" :disabled="disabled"  @change="form.plan_type = form.platform === 7 ? 2 : 1" />
        </el-form-item>
        <el-form-item label="Asin">
          <el-input v-model="form.asin" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="类型" prop="plan_type" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="form.plan_type" :disabled="disabled" placeholder="请选择" :options="options.plan_type" class="w-full" />
        </el-form-item>
        <el-form-item label="国家" prop="country" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="form.country" :options="options.country" class="w-full" placeholder="请选择" @change="form.destination_warehouse = ''" />
        </el-form-item>
        <el-form-item label="数量（注意:变更的是余料数量）" prop="plan_num" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <el-input-number v-model="form.plan_num" controls-position="right" placeholder="请输入" :min="0" :step="1" :precision="0" class="w-full" />
        </el-form-item>
        <el-form-item label="销售" prop="sale_id" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VCascader v-model="form.sale_id" :disabled="disabled" class="w-full" placeholder="请选择" @change="val => saleChange(form, val)" />
        </el-form-item>
        <el-form-item label="部门">
          <el-input :value="form.department_name" placeholder="请选择" disabled class="w-full" />
        </el-form-item>
        <el-form-item label="运输方式" prop="transport_type" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="form.transport_type" placeholder="请选择" :options="options.transport_type" :disabled="disabled" class="w-full" />
        </el-form-item>
        <el-form-item label="计划预计下单时间" prop="expect_order_time" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-date-picker v-model="form.expect_order_time" placeholder="日期选择" type="date" value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item label="预计交期" prop="pre_delivery_time" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-date-picker v-model="form.pre_delivery_time" type="date" value-format="YYYY-MM-DD" class="w-full" />
        </el-form-item>
        <el-form-item label="目的仓" prop="destination_warehouse" :rules="[{ required: form.plan_type !== 2, message: '不能为空', trigger: 'blur' }]">
          <VSelect v-model="form.destination_warehouse" placeholder="请选择" :options="form.country === 'US' ? options.destination_warehouse : options.plan_destination_warehouse" class="w-full" />
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.remark" placeholder="请输入" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
import { getDepartment } from '@/api/public'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const success = ref(false)
const disabled = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

const saleChange = (form, { value }) => {
  getDepartment({ select_user_id: value }).then(res => {
    form.department_id = res.data.department_id
    form.department_name = res.data.department_name
  })
}

const skuValidate = async (rule, sku, cb) => {
  if (!sku) cb('不能为空')
  const res = await api.getSku({ sku })
  const item = res.data.find(d => d.sku === sku)
  if (item) {
    const { sku_cn_title: sku_name, price_exclude_tax: unit_price, price_include_tax: unit_price_tax } = item
    form.value = Object.assign({}, form.value, item, { sku_name, unit_price, unit_price_tax })
    cb()
  } else {
    cb(new Error('请输入正确的sku'))
  }
}

// 打开弹窗
const open = async (id, disab = false) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {}
  loadings = reactive({})
  success.value = false
  visible.value = true
  disabled.value = disab
  formRef?.value?.resetFields()
  // 编辑
  if (id) {
    const res = await api.detail({ pp_id: id })
    form.value = res.data
  }
  
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const create = async (formRef) => {
  if (!await formRef.validate()) return
  loadings.create = true
  api[disabled.value ? 'change' : form.value.pp_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    success.value = true
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>